from sqlalchemy.orm import Session # 会话
from . import models,schemas #模式
from sqlalchemy.sql import func

def create_user(db:Session, user: schemas.UserCreate):
    id= db.query(func.max(models.User.id)).scalar() + 1
    # print(id)
    # print(**user.dict())
    db_user= models.User(**user.dict(), id=id)
    # print(db_user.to_dict())
    db.add(db_user)
    try:
        db.commit()
    except:
        db.rollback()
    db.refresh(db_user)
    return id


def update_user(db:Session, user: schemas.User):
    id=user.id
    db.query(models.User).filter(models.User.id == id).update(**user.dict(exclude={'id'}))
    try:
        db.commit()
    except:
        db.rollback()
    # db.refresh(db_user)
    return id

# 通过id查询用户信息
def get_user(db: Session, user_id: int):
    return db.query(models.User).filter(models.User.id == user_id).first()

def getall_user(db: Session):
    return db.query(models.User).filter().all()

def get_point(db: Session, user_id: int):
    return db.query(models.Pointitem).filter(models.Pointitem.user_id == user_id).all()

def getall_point(db: Session):
    return db.query(models.Pointitem).filter().all()

def get_pointbytime(db:Session,starttime,endtime):
    return db.query(models.Pointitem).filter(models.Pointitem.pointtime < endtime).filter(
        models.Pointitem.pointtime > starttime).all()
#                                 # 过滤器
# # 通过email查询用户信息
# def get_user_by_email(db: Session, email: str):
#     return db.query(models.User).filter(models.User.email == email).first()
#
# # 通过id范围查询用户信息
# def get_users(db: Session, skip: int = 0, limit: int = 100):
#                          # 初值           末值
#     return db.query(models.User).offset(skip).limit(limit).all()
#
# # 新建用户
# def create_user(db: Session, user: schemas.UserCreate):
#     fake_hashed_password = user.password + "notreallyhashed"
#     db_user = models.User(email=user.email, hashed_password=fake_hashed_password)
#     db.add(db_user)
#     db.commit()
#     db.refresh(db_user)
#     return db_user
#
# # 获取用户拥有的项目
# def get_items(db: Session, skip: int = 0, limit: int = 100):
#     return db.query(models.Item).offset(skip).limit(limit).all()
#
# # 新建用户拥有的项目
# def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int):
#     db_item = models.Item(**item.dict(), owner_id=user_id)
#     db.add(db_item)
#     db.commit()
#     db.refresh(db_item)
#     return db_item
